#include "useryaogan.h"

#define ADC_CH_NUMBER   2
#define ADC_TIMERS      5
#define ADC_FILTER_NUN  1

uint16_t adcBuf[ADC_TIMERS][ADC_CH_NUMBER];
uint8_t yaoganX,yaoganY;   //最后得出0-100的值


static unsigned int user_adcFilter(uint8_t ch);
static uint8_t user_adcConvert(uint32_t value);

void userYaoganScan()
{
	uint32_t tmpValue0,tmpValue1;
	uint8_t tmpConvert0,tmpConvert1;
	for(uint8_t j=0;j<ADC_TIMERS;j++)
	{
		for(uint8_t i=0;i<2;i++)
		{
			HAL_ADC_Start(&hadc);
			HAL_ADC_PollForConversion(&hadc,0xffff);
			adcBuf[j][i]=HAL_ADC_GetValue(&hadc);
//			printf("---times:%d---ch:%d--%d-------",j,i,adcBuf[j][i]);
		}
//		printf("\r\n");
	}
	HAL_ADC_Stop(&hadc);
	//滤波
	tmpValue0=user_adcFilter(0);
	tmpValue1=user_adcFilter(1);
	//转换成0-100
	tmpConvert0=user_adcConvert(tmpValue0);
	tmpConvert1=user_adcConvert(tmpValue1);
	
	if(((tmpConvert0-yaoganY)>10)||(yaoganY-tmpConvert0)>10)
	{
		HAL_GPIO_TogglePin(LED_GPIO_Port,LED_Pin);
	}
	if(((tmpConvert1-yaoganX)>10)||(yaoganX-tmpConvert1)>10)
	{
		HAL_GPIO_TogglePin(LED_GPIO_Port,LED_Pin);
	}		
	yaoganX=tmpConvert1;
	yaoganY=tmpConvert0;
	
	
//	printf("====value0==%d======",tmpConvert0);
//	printf("====value1==%d======\r\n",tmpConvert1);	
}

unsigned int user_adcFilter(uint8_t ch)
{
	unsigned char i,j;
	unsigned int change;
	unsigned int sum=0;
	unsigned int average;
	
	for(i=1;i<ADC_TIMERS;i++)							   
	{
		for(j=0;j<ADC_TIMERS-i;j++)
		{
			if(adcBuf[j][ch]>adcBuf[j+1][ch])
			{
				change=adcBuf[j+1][ch];
				adcBuf[j+1][ch]=adcBuf[j][ch];
				adcBuf[j][ch]=change;
			}			
		}
	}
	for(i=ADC_FILTER_NUN;i<ADC_TIMERS-ADC_FILTER_NUN;i++)  
	{
		sum+=adcBuf[i][ch];
	}	
	average=sum/(ADC_TIMERS-ADC_FILTER_NUN*2);			  
	return average;			
}
//把值转换成0-100
uint8_t user_adcConvert(uint32_t value)
{
	return value*100/4095;
}


uint8_t user_getYaoganValue(uint8_t xy)
{
	if(xy==YAOGAN_X)
	{
		return yaoganX;
	}
	else if(xy==YAOGAN_Y)
	{
		return yaoganY;
	}
	return 0;
}


